from django.shortcuts import render, HttpResponse, redirect, reverse
from course.models import Category, Course
from user.models import User
from django.http import StreamingHttpResponse
import re
import os

# Create your views here.
def index_handler(request):
    context = request.context

    print('1 context:', context)

    category_set = Category.objects.all()
    course_data_s = []
    for c in category_set:
        course_data_s.append(
            {
                'category': c.name,
                'course_s': c.categary_set.all()
            }
        )
    context['course_data_s'] = course_data_s

    return render(request, 'index.html', context=context)


def course_handler(request, course_id):
    context = request.context

    try:
        course = Course.objects.get(id=course_id)
        context['course'] = course

        context['view_perssion'] = False
        session_user = request.session['session_user']
        if session_user:
            if User.objects.filter(id=session_user.get('id'), userBuyer_set__id=course.id).exists():
                context['view_perssion'] = True

        return render(request, 'course.html', context)
    except:
        return HttpResponse(status=404)


def video_handler(request, course_id):
    context = request.context
    session_user = request.session['session_user']

    if not session_user:
        return redirect(reverse('course:course', args=(course_id,)))

    try:
        user = User.objects.get(id=session_user.get('id'))
        course = Course.objects.get(id=course_id)
        if user.userBuyer_set.filter(id=course.id).exists():
            context['course'] = course
            return render(request, 'video.html', context)
        else:
            return redirect(reverse('course:course', args=(course_id,)))
    except:
        return HttpResponse(status=404)


def videoStream_handler(request, course_id):

    def read_stream(filepath, begin_pos, len_per_time):
        with open(filepath, 'rb') as f:
            f.seek(begin_pos)
            while True:
                data = f.read(len_per_time)
                if data:
                    yield data
                else:
                    break

    session_user = request.session['session_user']

    if not session_user:
        return redirect(reverse('course:course', args=(course_id,)))

    try:
        user = User.objects.get(id=session_user.get('id'))
        course = Course.objects.get(id=course_id)
        if user.userBuyer_set.filter(id=course.id).exists():
            file_size = os.path.getsize(str(course.fileName))
            print('file size', file_size)
            range_value = request.headers.get('range')
            re_res = re.findall('=(\d+)-', range_value)
            if len(re_res) == 0:
                begin_pos = 0
            else:
                begin_pos = int(re_res[0])

            re_res = re.findall('-(\d+)', range_value)
            if len(re_res) == 0:
                if 0 == file_size:
                    end_pos = -1
                else:
                    end_pos = file_size - 1
            else:
                end_pos = int(re_res[0])

            if end_pos < begin_pos:
                this_len = 0
            else:
                this_len = end_pos - begin_pos + 1

            if this_len > 1024 * 1024: #最多一次1M
                this_len = 1024 * 1024
                end_pos = begin_pos + this_len - 1

            print('begin_pos', begin_pos)
            print('end_pos', end_pos)
            print('this_len', this_len)

            resp = StreamingHttpResponse(
                read_stream(str(course.fileName),
                            begin_pos,
                            this_len
                            ),
                status=206
            )
            resp['Content-Length'] = str(this_len)
            resp['Content-Range'] = 'bytes {}-{}/{}'.format(begin_pos, end_pos, file_size)

            print('Content-Length:', resp['Content-Length'])
            print('Content-Range:', resp['Content-Range'])

            return resp
        else:
            return redirect(reverse('course:course', args=(course_id,)))
    except:
        raise
        return HttpResponse(status=404)
